package com.example.module.custom.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.example.module.custom.R;
import com.example.module.custom.R2;
import com.example.module.custom.adapter.ProduceCodeAdapter;
import com.example.module.custom.adapter.ProgressCodeAdapter;
import com.example.module.custom.bean.MaterialsCodeBean;
import com.example.module.custom.bean.PlanBean;
import com.example.module.custom.http.HTTPURL;
import com.example.module.custom.utils.SoftKeyboardUtil;
import com.example.module.custom.utils.ToastUtil;
import com.example.module.custom.view.WheelView2;
import com.example.zhouwei.library.CustomPopWindow;
import com.google.gson.Gson;
import com.lzy.okgo.model.HttpParams;
import com.nand.library.base.base.BaseActivity;
import com.nand.library.base.bean.ResponseBean;
import com.nand.library.base.http.MyCallback;
import com.nand.library.base.http.OkGoUtils;
import com.nand.library.base.utils.SpUtils;
import com.nand.library.zxing.activity.CaptureActivity;
import com.nand.library.zxing.activity.CodeUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @name BlockDemo
 * @class name：com.example.module.custom.ui
 * @classdescribe 生产执行
 * @anthor ljp
 * @time 2020/2/23 14:22
 */
@Route(path = "/custom/PExecution")
public class ProductionExecutionActivity extends BaseActivity {
    public static final int DEVICE_NUMBER = 1000;//设备编码
    public static final int MATERIALS_NUMBER = 1001;//物料编码
    public static final int VEHICLE_NUMBER = 1002;//载具编码
    @BindView(R2.id.real_back)
    RelativeLayout realBack;
    @BindView(R2.id.tv_headline)
    TextView tvHeadline;
    @BindView(R2.id.tv_day_plan)
    TextView tvDayPlan;
    @BindView(R2.id.image_plan)
    ImageView imagePlan;
    @BindView(R2.id.linear_plan)
    LinearLayout linearPlan;
    @BindView(R2.id.tv_inspection_type)
    TextView tvInspectionType;
    @BindView(R2.id.image_process)
    ImageView imageProcess;
    @BindView(R2.id.linear_process)
    LinearLayout linearProcess;
    @BindView(R2.id.et_equipment_number)
    EditText etEquipmentNumber;
    @BindView(R2.id.image_work_in_progress_batch)
    ImageView imageWorkInProgressBatch;
    @BindView(R2.id.recycler_materials)
    RecyclerView recyclerMaterials;
    @BindView(R2.id.linear_materials)
    LinearLayout linearMaterials;
    @BindView(R2.id.recycler_work_progress)
    RecyclerView recyclerWorkProgress;
    @BindView(R2.id.linear_work_progress)
    LinearLayout linearWorkProgress;
    @BindView(R2.id.btn_replace_material)
    Button btnReplaceMaterial;
    @BindView(R2.id.btn_replace_wip)
    Button btnReplaceWip;
    @BindView(R2.id.btn_increase_output)
    Button btnIncreaseOutput;
    @BindView(R2.id.btn_increase_scrap)
    Button btnIncreaseScrap;
    @BindView(R2.id.linear_btn)
    LinearLayout linearBtn;
    @BindView(R2.id.tv_replace_number)
    TextView tvReplaceNumber;
    @BindView(R2.id.btn_replace_sure)
    Button btnReplaceSure;
    @BindView(R2.id.linear_replace)
    LinearLayout linearReplace;
    @BindView(R2.id.text_scan_num)
    TextView textScanNum;
    @BindView(R2.id.btn_add_sure)
    Button btnAddSure;
    @BindView(R2.id.linear_output)
    LinearLayout linearOutput;
    @BindView(R2.id.btn_addnum_sure)
    Button btnAddnumSure;
    @BindView(R2.id.text_add_num_show)
    TextView textAddNumShow;
    @BindView(R2.id.btn_print)
    Button btnPrint;
    @BindView(R2.id.linear_show_num)
    LinearLayout linearShowNum;
    @BindView(R2.id.linear_no_output)
    LinearLayout linearNoOutput;
    @BindView(R2.id.linear_add_output)
    LinearLayout linearAddOutput;
    @BindView(R2.id.tv_increase_scrap)
    TextView tvIncreaseScrap;
    @BindView(R2.id.image_increase_scrap)
    ImageView imageIncreaseScrap;
    @BindView(R2.id.linear_add_scrap)
    LinearLayout linearAddScrap;
    @BindView(R2.id.linear_show)
    LinearLayout linearShow;
    @BindView(R2.id.edit_out_num)
    EditText editOutNum;
    @BindView(R2.id.edit_no_out_num)
    EditText editNoOutNum;
    @BindView(R2.id.linear_enter)
    LinearLayout linearEnter;
    @BindView(R2.id.edit_bad_num)
    EditText editBadNum;

    private CustomPopWindow mCustomPopWindow;
    private WheelView2 mWheelview;
    private TextView mTvConfirm;
    private TextView mTvCancel;
    private ArrayList<PlanBean.DataListBean> dataListBeansPlan;
    private ArrayList<PlanBean.DataListBean> dataListBeansProcess;
    //不良原因列表
    private ArrayList<PlanBean.DataListBean> dataListBeansBads;
    private String planOid;//日计划oid
    private String planId;//日计划单据号
    private String processOid;//工序oid
    private String badOid;//不良原因oid
    private ArrayList<MaterialsCodeBean.DataListBean> materialList;
    private ArrayList<MaterialsCodeBean.DataListBean> materialListProgress;
    private ProduceCodeAdapter produceCodeAdapter;
    private ProgressCodeAdapter progressCodeAdapter;
    private String deviceCode;
    private String wipLotIndex;//在制品指数
    private String wipLot;//在制品编码
    private String noOutNum;
    private int tray;//是否产出载具
    private String vehicleCoding;//扫描得到载具编码
    private int userId;
    private OptionsPickerView dayPlanPicker,processPicker,badPicker;
    private int selectedPositionDay = 0;//当前选定的日计划位置
    private int selectedPositionProcess = 0;//当前选定的工序位置
    private int selectedPositionBad = 0;//当前选定的不良原因位置
    @Override
    protected int initLayout() {
        return R.layout.activity_production_executio;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
    }

    @Override
    protected void initData() {
        userId = SpUtils.readInt(this, "userId", 0);
        dataListBeansPlan = new ArrayList<>();
        dataListBeansProcess = new ArrayList<>();
        dataListBeansBads = new ArrayList<>();
        httpPlan(HTTPURL.PRODUCE_DAY_PLAN, dataListBeansPlan);
        httpPlan(HTTPURL.PRODUCE_PROCESS, dataListBeansProcess);

        materialList = new ArrayList<>();
        materialListProgress = new ArrayList<>();
        produceCodeAdapter = new ProduceCodeAdapter(mContext, materialList, R.layout.item_produce_code);
        recyclerMaterials.setLayoutManager(new LinearLayoutManager(mContext));
        produceCodeAdapter.addHeaderView(R.layout.item_produce_code);
        recyclerMaterials.setAdapter(produceCodeAdapter);

        progressCodeAdapter = new ProgressCodeAdapter(mContext, materialListProgress, R.layout.item_produce_code);
        recyclerWorkProgress.setLayoutManager(new LinearLayoutManager(mContext));
        progressCodeAdapter.addHeaderView(R.layout.item_produce_code);
        recyclerWorkProgress.setAdapter(progressCodeAdapter);
        etEquipmentNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
            @Override
            public void afterTextChanged(Editable editable) {
                deviceCode = editable.toString().trim();
            }
        });

        etEquipmentNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((actionId == 0 || actionId == 3) && event != null) {
                    deviceCode= etEquipmentNumber.getText().toString().trim();
                    Log.i(TAG, "onEditorAction: ---search-----" + deviceCode);
                    etEquipmentNumber.setText(deviceCode);
                    etEquipmentNumber.setSelection(deviceCode.length());

                    linearShow.setVisibility(View.GONE);
                    layoutGone();
                    setEnableTrue();
                    httpListData();
                    httpListDataProgress();
                    SoftKeyboardUtil.hideKeyboard(activity);
                    return true;
                }
                return false;
            }
        });

       initPicker();
    }
    /**
     *  @author ljp
     *  @time   14:46
     *  @describe 选择器实例化
     */
    private void initPicker() {
        dayPlanPicker = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                selectedPositionDay = options1;
                planOid = dataListBeansPlan.get(options1).getOid();
                planId = dataListBeansPlan.get(options1).getDayPlanID();
                tvDayPlan.setText(dataListBeansPlan.get(options1).getDayPlanID());
                linearShow.setVisibility(View.GONE);
                layoutGone();
                setEnableTrue();
                httpListData();
                httpListDataProgress();
            }
        }).setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
            @Override
            public void onOptionsSelectChanged(int options1, int options2, int options3) {
                if (options1 !=  selectedPositionDay) {
                    selectedPositionDay = options1;
                    dayPlanPicker.setSelectOptions(options1);
                }
            }
        }).setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setSubCalSize(16)//确定和取消文字大小
                .setSubmitColor(Color.GRAY)//确定按钮文字颜色
                .setCancelColor(Color.GRAY)//取消按钮文字颜色
                .setContentTextSize(20)//滚轮文字大小
                .setSelectOptions(selectedPositionDay)
                .setCyclic(false, false, false)//循环与否
                .build();
        processPicker = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //gzlbID = options1;
                // tvInspectionType.setText(options1Items.get(options1));
                selectedPositionProcess = options1;
                processOid = dataListBeansProcess.get(options1).getOid();
                tvInspectionType.setText(dataListBeansProcess.get(options1).getProcessContent());
                linearShow.setVisibility(View.GONE);
                layoutGone();
                setEnableTrue();
                httpListData();
                httpListDataProgress();
            }
        }).setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
            @Override
            public void onOptionsSelectChanged(int options1, int options2, int options3) {
                if (options1 !=  selectedPositionProcess) {
                    selectedPositionProcess = options1;
                    processPicker.setSelectOptions(options1);
                }
            }
        }).setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setSubCalSize(16)//确定和取消文字大小
                .setSubmitColor(Color.GRAY)//确定按钮文字颜色
                .setCancelColor(Color.GRAY)//取消按钮文字颜色
                .setContentTextSize(20)//滚轮文字大小
                .setCyclic(false, false, false)//循环与否
                .build();
        badPicker = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                badOid = dataListBeansBads.get(options1).getOid();
                tvIncreaseScrap.setText(dataListBeansBads.get(options1).getBadName());
            }
        }).setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
            @Override
            public void onOptionsSelectChanged(int options1, int options2, int options3) {
                if (options1 !=  selectedPositionBad) {
                    selectedPositionBad = options1;
                    badPicker.setSelectOptions(options1);
                }
            }
        }).setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setSubCalSize(16)//确定和取消文字大小
                .setSubmitColor(Color.GRAY)//确定按钮文字颜色
                .setCancelColor(Color.GRAY)//取消按钮文字颜色
                .setContentTextSize(20)//滚轮文字大小
                .setCyclic(false, false, false)//循环与否
                .build();

    }
    /**
     * @author ljp
     * @time 15:26
     * @describe 工序 日计划请求
     */
    private void httpPlan(final String url, final List<PlanBean.DataListBean> dataListBeans) {
        OkGoUtils.getInstance().post(this, url, null,
                1, true, new MyCallback() {
                    @Override
                    public void onSuccess(ResponseBean response, int id) {
                        if (response.getCode() == 200) {
                            String data = response.getDataInfo().toString();
                            // Log.i(TAG, "onSuccess: ---data------"+response.getDataList().toString());
                            PlanBean planBean = new Gson().fromJson(data, PlanBean.class);
                            dataListBeans.addAll(planBean.getDataList());
                            if(planBean.getDataList().size() != 0) {
                                if (url == HTTPURL.PRODUCE_DAY_PLAN) {//日计划
                                    tvDayPlan.setText(dataListBeans.get(0).getDayPlanID());
                                    planOid = dataListBeans.get(0).getOid();
                                    planId = dataListBeans.get(0).getDayPlanID();
                                } else {
                                    tvInspectionType.setText(dataListBeans.get(0).getProcessContent());
                                    processOid = dataListBeans.get(0).getOid();
                                }
                            }
                            Log.i(TAG, "onSuccess: -----dataListBeans-----" + dataListBeans.size());
                        } else {
                            ToastUtil.showShortToast(response.getMsg(), mContext);
                        }
                    }

                    @Override
                    public void onError(Throwable e, int id) {

                    }
                });
    }

    /**
     * @author ljp
     * @time 17:44
     * @describe 根据日计划 工序  设备编码查询物料批次信息
     */
    private void httpListData() {
        String s = etEquipmentNumber.getText().toString();
        if(TextUtils.isEmpty(planOid)){
            return;
        }
        if(TextUtils.isEmpty(processOid)){
            return;
        }
        if(TextUtils.isEmpty(s)){
            return;
        }
        HttpParams httpParams = new HttpParams();
        httpParams.put("current",1);
        httpParams.put("size",10);
        httpParams.put("fmmProcessOid",processOid);//工序oid
        httpParams.put("dayPlanID",planOid);//日计划oid
        httpParams.put("fEQDetailOid",s);//设备编码
        OkGoUtils.getInstance().post(this, HTTPURL.PRODUCE_MATERIALS, httpParams,
                1, true, new MyCallback() {
                    @Override
                    public void onSuccess(ResponseBean response, int id) {
                        if (response.getCode() == 200) {
                            Log.i(TAG, "onSuccess: -----" + response.toString());
                            if (response.getDataInfo()!= null) {
                                String data = response.getDataInfo().toString();
                                // Log.i(TAG, "onSuccess: ---data------"+response.getDataList().toString());
                                MaterialsCodeBean materialsCodeBean = new Gson().fromJson(data, MaterialsCodeBean.class);
                                if (materialsCodeBean.getDataList() != null && materialsCodeBean.getDataList().size() != 0) {
                                    linearMaterials.setVisibility(View.VISIBLE);
                                    showBtn();
                                    materialList.clear();
                                    materialList.addAll(materialsCodeBean.getDataList());
                                    produceCodeAdapter.notifyDataSetChanged();
                                } else {
                                    linearMaterials.setVisibility(View.GONE);
                                }
                            }else {
                                //ToastUtil.showShortToast("未查询到此设备信息", mContext);
                            }
                                //Log.i(TAG, "onSuccess: -----dataListBeans-----"+dataListBeans.size());
                            } else {
                                ToastUtil.showShortToast(response.getMsg(), mContext);
                            }

                    }

                    @Override
                    public void onError(Throwable e, int id) {

                    }
                });
        showScrap();
    }

    /**
     * @author ljp
     * @time 17:44
     * @describe 根据日计划 工序  设备编码查询在制品列表信息
     */
    private void httpListDataProgress() {
        String s = etEquipmentNumber.getText().toString().trim();
        if(TextUtils.isEmpty(planOid)){
            return;
        }
        if(TextUtils.isEmpty(processOid)){
            return;
        }
        if(TextUtils.isEmpty(s)){
            return;
        }
        HttpParams httpParams = new HttpParams();
       // httpParams.put("current",1);
       // httpParams.put("size",10);
        httpParams.put("fmmProcessOid",processOid);//工序oid
        httpParams.put("dayPlanID",planOid);//日计划oid
        httpParams.put("fEQDetailOid",s);//设备编码
        //Log.i(TAG, "httpListDataProgress: -----httpParams--------"+httpParams.toString());
        OkGoUtils.getInstance().post(this, HTTPURL.PRODUCE_PROGRESS, httpParams,
                2, true, new MyCallback() {
                    @Override
                    public void onSuccess(ResponseBean response, int id) {
                        if (response.getCode() == 200) {
                            String data = response.getDataInfo().toString();
                            // Log.i(TAG, "onSuccess: ---data------"+response.getDataList().toString());
                            MaterialsCodeBean materialsCodeBean = new Gson().fromJson(data, MaterialsCodeBean.class);
                            if(materialsCodeBean.getDataList() != null && materialsCodeBean.getDataList().size() != 0){
                                showBtn();
                                linearWorkProgress.setVisibility(View.VISIBLE);
                                materialListProgress.clear();
                                materialListProgress.addAll(materialsCodeBean.getDataList());
                                progressCodeAdapter.notifyDataSetChanged();
                            }else {
                                //ToastUtil.showShortToast("未查询到此设备信息", mContext);
                                linearWorkProgress.setVisibility(View.GONE);
                            }
                            //Log.i(TAG, "onSuccess: -----dataListBeans-----"+dataListBeans.size());
                        } else {
                            ToastUtil.showShortToast(response.getMsg(), mContext);
                        }
                    }

                    @Override
                    public void onError(Throwable e, int id) {

                    }
                });
        showScrap();
    }

    @SuppressLint("InvalidR2Usage")
    @OnClick({R2.id.real_back, R2.id.btn_add_sure, R2.id.btn_replace_material,
            R2.id.btn_replace_wip, R2.id.btn_increase_output,
            R2.id.btn_increase_scrap, R2.id.image_work_in_progress_batch, R2.id.btn_addnum_sure,
            R2.id.linear_plan, R2.id.text_scan_num, R2.id.linear_process,
            R2.id.btn_replace_sure, R2.id.linear_add_scrap, R2.id.btn_bad_sure})
    public void onViewClicked(View view) {
        SoftKeyboardUtil.hideKeyboard(activity);
        int id = view.getId();
        if (id == R.id.real_back) {
            finish();
        } else if (id == R.id.btn_addnum_sure) {//不产出载具确认
            noOutNum = editNoOutNum.getText().toString().trim();
            if (!TextUtils.isEmpty(noOutNum)) {
                httpNoVehicle();
            } else {
                ToastUtil.showShortToast("请输入产出数量", mContext);
            }
        } else if (id == R.id.btn_add_sure) {//产出载具确认
            if (!TextUtils.isEmpty(editOutNum.getText().toString().trim())) {
                if (!TextUtils.isEmpty(vehicleCoding)) {
                    httpVehicle();
                } else {
                    ToastUtil.showShortToast("请扫描载具编码", mContext);
                }
            } else {
                ToastUtil.showShortToast("请输入产出数量", mContext);
            }
        } else if (id == R.id.btn_replace_material) {//更换物料
            Intent intent = new Intent(mContext, CaptureActivity.class);
            startActivityForResult(intent, MATERIALS_NUMBER);
            tvReplaceNumber.setText("");
            layoutGone();
            Log.i(TAG, "onViewClicked: --------------");
            //扫描物料批次码，显示
            setEnable(btnReplaceMaterial);

        } else if (id == R.id.btn_replace_wip) {//更换WIP
            //扫描物料批次码，显示
            Intent intent = new Intent(mContext, CaptureActivity.class);
            startActivityForResult(intent, MATERIALS_NUMBER);
            //btnNotClickable();
            setEnable(btnReplaceWip);
            layoutGone();
            tvReplaceNumber.setText("");
        } else if (id == R.id.btn_increase_output) {//增加产出
            //需要先判断当前工序是否产出载具
            layoutGone();
            httpJudeProgress();
            setEnable(btnIncreaseOutput);
        } else if (id == R.id.btn_increase_scrap) {//增加报废
            layoutGone();
            setEnable(btnIncreaseScrap);
            linearAddScrap.setVisibility(View.VISIBLE);
            httpBadList();
        } else if (id == R.id.linear_add_scrap) {//不良原因选项
            //initPop1Bad();
            badPicker.setPicker(dataListBeansBads);
            badPicker.show();
        } else if (id == R.id.image_work_in_progress_batch) {//扫描设备编码
            Intent intent = new Intent(this, CaptureActivity.class);
            startActivityForResult(intent, DEVICE_NUMBER);
        } else if (id == R.id.linear_plan) {//日计划
            //initPop1(dataListBeansPlan, true);
            dayPlanPicker.setPicker(dataListBeansPlan);
            dayPlanPicker.show();
        } else if (id == R.id.text_scan_num) {//点击扫描载具编码
            Intent intent = new Intent(this, CaptureActivity.class);
            startActivityForResult(intent, VEHICLE_NUMBER);
        } else if (id == R.id.linear_process) {//工序
            //initPop1(dataListBeansProcess, false);
            processPicker.setPicker(dataListBeansProcess);
            processPicker.show();
        } else if (id == R.id.btn_replace_sure) {//更换物料，更换WIP确认
            deviceCode = etEquipmentNumber.getText().toString().trim();
            String s = tvReplaceNumber.getText().toString();
            httpReplace(deviceCode, HTTPURL.PRODUCE_MATERIALS, s, "");
        } else if (id == R.id.btn_bad_sure) {//确认增加报废
            String badNum = editBadNum.getText().toString().trim();
            if(!TextUtils.isEmpty(badNum) && !TextUtils.isEmpty(etEquipmentNumber.getText().toString().trim())){
                httpCheck(badNum);
            }else if(TextUtils.isEmpty(etEquipmentNumber.getText().toString().trim())){
                ToastUtil.showShortToast("请输入设备编号", mContext);
            }else {
                ToastUtil.showShortToast("请输入不良数量", mContext);
            }
        }
    }
    /**
     *  @author ljp
     *  @time   16:03
     *  @describe 校验设备编码是否存在
     */
    private void httpCheck(final String badNum) {
        HttpParams httpParams = new HttpParams();
        httpParams.put("equipID",deviceCode);//设备编码
        OkGoUtils.getInstance().post(this, HTTPURL.PRODUCE_CHECK_CODE, httpParams,
                1, false, new MyCallback() {
                    @Override
                    public void onSuccess(ResponseBean response, int id) {
                        Log.e(TAG, "httpCheck--------onSuccess: ----"+response.toString());
                        if (response.getCode() == 200) {
                            httpBadSubmit(badNum);
                        } else if(response.getCode() == 114){
                            ToastUtil.showShortToast("设备编码有误，请重新输入", mContext);
                        }else {
                            ToastUtil.showShortToast(response.getMsg(),mContext);
                        }
                    }

                    @Override
                    public void onError(Throwable e, int id) {
                    }
                });
    }

    /**
     *  @author ljp
     *  @time   10:04
     *  @describe 增加报废原因确认提交
     */
    private void httpBadSubmit(String num){
        HttpParams httpParams = new HttpParams();
        httpParams.put("oid",badOid);//不良原因oid
        httpParams.put("badQuantity",num);//不良数量
        httpParams.put("dayPlanID",planOid);//日计划oid
        httpParams.put("fmmProcessOid",processOid);//工序oid
        httpParams.put("fEQDetailOid",deviceCode);//设备编码
        httpParams.put("userId", userId);//设备编码
        OkGoUtils.getInstance().post(this, HTTPURL.PRODUCE_ADD_SCRAPPEN, httpParams,
                1, false, new MyCallback() {
                    @Override
                    public void onSuccess(ResponseBean response, int id) {
                        if (response.getCode() == 200) {
                            editBadNum.setText("");
                            linearAddScrap.setVisibility(View.GONE);
                            setEnableTrue();
                            ToastUtil.showShortToast("提交成功", mContext);
                            Log.i(TAG, "onSuccess: ----"+response.toString());
                        } else {
                            ToastUtil.showShortToast(response.getMsg(), mContext);
                        }
                    }

                    @Override
                    public void onError(Throwable e, int id) {
                    }
                });
    }

    /**
     * @author ljp
     * @time 11:32
     * @describe 不良原因选择popu
     */
    private void initPop1Bad() {
        //创建并显示popWindow
        View view = View.inflate(mContext, R.layout.popup_item_list2, null);
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(mContext)
                .setView(view)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.7f) // 控制亮度
                .setAnimationStyle(R.style.pop_anim_style)
                .create()
                .showAtLocation(tvDayPlan, Gravity.BOTTOM, 0, 0);
        mWheelview = (WheelView2) view.findViewById(R.id.wheel_view_list);
        mTvConfirm = view.findViewById(R.id.tv_confirm);
        mTvCancel = view.findViewById(R.id.tv_cancel);
        mWheelview.setOffset(1);
        mWheelview.setItems(dataListBeansBads);
        mWheelview.setSeletion(0);
        mWheelview.setOnWheelViewListener(new WheelView2.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, PlanBean.DataListBean ite) {
                badOid = ite.getOid();
                // Log.i(TAG, "onSelected: ----ite-----"+ite.toString());
                //Log.i(TAG, "onSelected: ---planOid---"+planOid+"---processOid--"+processOid+"---planId-------"+planId);
            }
        });
        mTvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String seletedItem = mWheelview.getSeletedItem();
                tvIncreaseScrap.setText(seletedItem);
                mCustomPopWindow.dissmiss();
            }
        });

        mTvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCustomPopWindow.dissmiss();
            }
        });
    }

    /**
     * @author ljp
     * @time 17:27
     * @describe 不良原因列表
     */
    private void httpBadList() {
        OkGoUtils.getInstance().post(this, HTTPURL.PRODUCE_BAD_CAUSES, null,
                1, false, new MyCallback() {
                    @Override
                    public void onSuccess(ResponseBean response, int id) {
                        if (response.getCode() == 200) {
                            String s = response.getDataInfo().toString();
                            PlanBean planBean = new Gson().fromJson(s, PlanBean.class);
                            if(planBean.getDataList()!= null &&planBean.getDataList().size()!= 0) {
                                dataListBeansBads.addAll(planBean.getDataList());
                                tvIncreaseScrap.setText(dataListBeansBads.get(0).getBadName());
                                badOid = dataListBeansBads.get(0).getOid();
                            }
                        } else {
                            ToastUtil.showShortToast(response.getMsg(), mContext);
                        }
                    }

                    @Override
                    public void onError(Throwable e, int id) {
                    }
                });
    }

    /**
     * @author ljp
     * @time 16:34
     * @describe 产出载具确认
     */
    private void httpVehicle() {
        if (!TextUtils.isEmpty(wipLot) && !TextUtils.isEmpty(wipLotIndex)) {
            HttpParams httpParams = new HttpParams();
            httpParams.put("wipLot", wipLot);//在制品编码
            httpParams.put("trayLot", vehicleCoding);//载具编码
            httpParams.put("outputQuantity", editOutNum.getText().toString().trim());//产出数量
            httpParams.put("dayPlanID", planOid);//日计划oid
            httpParams.put("fmmProcessOid", processOid);//工序oid
            httpParams.put("fEQDetailOid", deviceCode);//设备编码
            httpParams.put("tray", tray);//是否产出载具 0否 1是
            httpParams.put("userId", userId);//用户id
            httpParams.put("wipLotIndex", wipLotIndex);//在制品指数
            OkGoUtils.getInstance().post(this, HTTPURL.PRODUCE_INCREASE_OUTPUT, httpParams,
                    1, false, new MyCallback() {
                        @Override
                        public void onSuccess(ResponseBean response, int id) {
                            if (response.getCode() == 200) {
                                linearOutput.setVisibility(View.GONE);
                                // linearShowNum.setVisibility(View.VISIBLE);
                                ToastUtil.showShortToast("增加成功", mContext);
                                //textAddNumShow.setText("在制品编码：" + wipLot);
                                setEnableTrue();
                                Log.i(TAG, "onSuccess: ---data------" + response.toString());
                            } else {
                                ToastUtil.showShortToast(response.getMsg(), mContext);
                            }
                        }

                        @Override
                        public void onError(Throwable e, int id) {

                        }
                    });
        }
    }

    /**
     * @author ljp
     * @time 16:34
     * @describe 不产出载具确认
     */
    private void httpNoVehicle() {
        if (!TextUtils.isEmpty(wipLot) && !TextUtils.isEmpty(wipLotIndex)) {
            HttpParams httpParams = new HttpParams();
            httpParams.put("wipLot", wipLot);//在制品编码
            httpParams.put("outputQuantity", noOutNum);//产出数量
            httpParams.put("dayPlanID", planOid);//日计划oid
            httpParams.put("fmmProcessOid", processOid);//工序oid
            httpParams.put("fEQDetailOid", deviceCode);//设备编码
            httpParams.put("tray", tray);//是否产出载具 0否 1是
            httpParams.put("userId", userId);//用户id
            httpParams.put("wipLotIndex", wipLotIndex);//在制品指数
            OkGoUtils.getInstance().post(this, HTTPURL.PRODUCE_INCREASE_OUTPUT, httpParams,
                    1, false, new MyCallback() {
                        @Override
                        public void onSuccess(ResponseBean response, int id) {
                            if (response.getCode() == 200) {
                                linearEnter.setVisibility(View.GONE);
                                linearShowNum.setVisibility(View.VISIBLE);
                                ToastUtil.showShortToast("增加成功", mContext);
                                textAddNumShow.setText("在制品编码：" + wipLot);

                                Log.i(TAG, "onSuccess: ---data------" + response.toString());
                            } else {
                                ToastUtil.showShortToast(response.getMsg(), mContext);
                            }
                        }

                        @Override
                        public void onError(Throwable e, int id) {

                        }
                    });
        }
    }

    /**
     * @author ljp
     * @time 15:24
     * @describe 工序是否产出载具判断
     */
    private void httpJudeProgress() {
        HttpParams httpParams = new HttpParams();
        httpParams.put("fMmProcessOid", processOid);//工序oid
        httpParams.put("dayPlanID", planOid);//日计划oid
        httpParams.put("processContent", tvInspectionType.getText().toString());//工序描述
        httpParams.put("fEQDetailOid", etEquipmentNumber.getText().toString().trim());//设备编码
        if(materialList.size() != 0){
            httpParams.put("type", 1);//数据类型 1物料 2在制品 3全部
        }
        if(materialListProgress.size() != 0){
            httpParams.put("type", 2);//数据类型 1物料 2在制品 3全部
        }
        if(materialList.size() != 0 && materialListProgress.size() != 0){
            httpParams.put("type", 3);//数据类型 1物料 2在制品 3全部
        }
        Log.i(TAG, "httpJudeProgress: -----------"+httpParams.toString());
        OkGoUtils.getInstance().post(this, HTTPURL.PRODUCE_IS_OUTPUT_VEHICLE, httpParams,
                1, false, new MyCallback() {
                    @Override
                    public void onSuccess(ResponseBean response, int id) {
                        if (response.getCode() == 200) {
                            String s = response.getDataInfo().toString();
                            Log.i(TAG, "onSuccess: ---工序是否产出载具判断--response---s--" + s);
                            try {
                                JSONObject jsonObject = new JSONObject(s);
                                /*if(!s.contains("tray") || TextUtils.isEmpty(jsonObject.get("tray").toString())){
                                    showToast("当前工序无法增加产出");
                                    setEnableTrue();
                                    layoutGone();
                                }else {*/
                                    tray = jsonObject.getInt("tray");
                                    if (tray == 0) {
                                        editNoOutNum.setText("");
                                        linearAddOutput.setVisibility(View.VISIBLE);
                                        linearNoOutput.setVisibility(View.VISIBLE);
                                        linearEnter.setVisibility(View.VISIBLE);
                                    } else {
                                        editOutNum.setText("");
                                        linearAddOutput.setVisibility(View.VISIBLE);
                                        linearOutput.setVisibility(View.VISIBLE);
                                    }
                                    generateWIP();
                              //  }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            ToastUtil.showShortToast(response.getMsg(), mContext);
                        }
                    }

                    @Override
                    public void onError(Throwable e, int id) {

                    }
                });

    }

    /**
     * @author ljp
     * @time 16:27
     * @describe 生成在制品编码
     */
    private void generateWIP() {
        HttpParams httpParams = new HttpParams();
        httpParams.put("fMmProcessOid", processOid);//工序oid
        httpParams.put("fEQDetailOid", deviceCode);//设备编码
        OkGoUtils.getInstance().post(this, HTTPURL.PRODUCE_GENERATE_WIP, httpParams,
                1, false, new MyCallback() {
                    @Override
                    public void onSuccess(ResponseBean response, int id) {
                        if (response.getCode() == 200) {
                            String s = response.getDataInfo().toString();
                            Log.i(TAG, "onSuccess: -----response---s--" + s);
                            try {
                                wipLotIndex = new JSONObject(s).getString("wipLotIndex");
                                wipLot = new JSONObject(s).getString("wipLot");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            ToastUtil.showShortToast(response.getMsg(), mContext);
                        }
                    }

                    @Override
                    public void onError(Throwable e, int id) {

                    }
                });
    }

    /**
     * @author ljp
     * @time 14:13
     * @describe 更换物料，更换WIP,确认
     */
    private void httpReplace(String code, String url, String partId, String trayLot) {
        HttpParams httpParams = new HttpParams();
        httpParams.put("fmmProcessOid", processOid);//工序oid
        httpParams.put("dayPlanID", planId);//日计划单据号
        httpParams.put("fEQDetailOid", code);//设备编码
        if (TextUtils.isEmpty(trayLot)) {
            httpParams.put("partId", partId);//物料编码
        } else {
            httpParams.put("trayLot", trayLot);//载具编码
        }
        OkGoUtils.getInstance().post(this, url, httpParams,
                1, false, new MyCallback() {
                    @Override
                    public void onSuccess(ResponseBean response, int id) {
                        if (response.getCode() == 200) {
                            ToastUtil.showShortToast("更换成功", mContext);
                            setEnableTrue();
                            layoutGone();
                            Log.i(TAG, "onSuccess: -----response-----" + response.toString());
                        } else {
                            ToastUtil.showShortToast(response.getMsg(), mContext);
                        }
                    }

                    @Override
                    public void onError(Throwable e, int id) {

                    }
                });

    }

    /**
     * @author ljp
     * @time 11:32                          
     * @describe 弹出列表选择popu
     */
    private void initPop1(List<PlanBean.DataListBean> dataListBeans, final boolean isPlan) {
        Log.i(TAG, "initPop1: ----dataListBeans--" + dataListBeans.size());
        //创建并显示popWindow
        View view = View.inflate(mContext, R.layout.popup_item_list2, null);
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(mContext)
                .setView(view)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.7f) // 控制亮度
                .setAnimationStyle(R.style.pop_anim_style)
                .create()
                .showAtLocation(tvDayPlan, Gravity.BOTTOM, 0, 0);
        mWheelview = (WheelView2) view.findViewById(R.id.wheel_view_list);
        mTvConfirm = view.findViewById(R.id.tv_confirm);
        mTvCancel = view.findViewById(R.id.tv_cancel);
        mWheelview.setOffset(1);
        mWheelview.setItems(dataListBeans);
        mWheelview.setSeletion(isPlan?selectedPositionDay:selectedPositionProcess);
        mWheelview.setOnWheelViewListener(new WheelView2.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, PlanBean.DataListBean ite) {
                if (isPlan) {
                    selectedPositionDay = selectedIndex -1;
                    planOid = ite.getOid();
                    planId = ite.getDayPlanID();
                } else {
                    selectedPositionProcess = selectedIndex -1;
                    processOid = ite.getOid();
                    Log.i(TAG, "onSelected: ----processOid-----"+processOid);
                }
                // Log.i(TAG, "onSelected: ----ite-----"+ite.toString());
                //Log.i(TAG, "onSelected: ---planOid---"+planOid+"---processOid--"+processOid+"---planId-------"+planId);
            }
        });
        mTvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String seletedItem = mWheelview.getSeletedItem();
                if (isPlan) {
                    tvDayPlan.setText(seletedItem);
                } else {
                    tvInspectionType.setText(seletedItem);
                }
                linearShow.setVisibility(View.GONE);
                layoutGone();
                setEnableTrue();
                httpListData();
                httpListDataProgress();
                mCustomPopWindow.dissmiss();
            }
        });

        mTvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCustomPopWindow.dissmiss();
            }
        });
    }

    /**
     * @author ljp
     * @time 10:06
     * @describe 按钮选中显示
     */
    private void setEnable(Button btn) {
        List<Button> buttonList = new ArrayList<>();
        if (buttonList.size() == 0) {
            buttonList.add(btnReplaceMaterial);
            buttonList.add(btnReplaceWip);
            buttonList.add(btnIncreaseOutput);
            buttonList.add(btnIncreaseScrap);
        }
        for (int i = 0; i < buttonList.size(); i++) {
            buttonList.get(i).setEnabled(true);
        }
        btn.setEnabled(false);
    }

    /**
     * @author ljp
     * @time 10:06
     * @describe 按钮还原
     */
    private void setEnableTrue() {
        btnReplaceMaterial.setEnabled(true);
        btnReplaceWip.setEnabled(true);
        btnIncreaseOutput.setEnabled(true);
        btnIncreaseScrap.setEnabled(true);
        tvReplaceNumber.setText("");
        textScanNum.setText("点击扫描载具编码");
        editNoOutNum.setText("");
        editBadNum.setText("");
        editOutNum.setText("");
        textAddNumShow.setText("");
        tvIncreaseScrap.setText("");
    }

    /**
     * @author ljp
     * @time 20:31
     * @describe 设置布局都隐藏
     */
    private void layoutGone() {
        linearReplace.setVisibility(View.GONE);
        linearAddOutput.setVisibility(View.GONE);
        linearAddScrap.setVisibility(View.GONE);
        linearOutput.setVisibility(View.GONE);
        linearNoOutput.setVisibility(View.GONE);
        linearEnter.setVisibility(View.GONE);
        linearShowNum.setVisibility(View.GONE);
    }
    /**
     *  @author ljp
     *  @time   15:07
     *  @describe 只显示报废按钮
     */
    private void showScrap(){
        linearShow.setVisibility(View.VISIBLE);
        btnIncreaseOutput.setVisibility(View.GONE);
        btnReplaceWip.setVisibility(View.GONE);
        btnReplaceMaterial.setVisibility(View.GONE);
        btnIncreaseScrap.setVisibility(View.VISIBLE);
    }
    /**
     *  @author ljp
     *  @time   15:07
     *  @describe 显示所有按钮
     */
    private void showBtn(){
        linearShow.setVisibility(View.VISIBLE);
        btnIncreaseOutput.setVisibility(View.VISIBLE);
        btnReplaceWip.setVisibility(View.VISIBLE);
        btnReplaceMaterial.setVisibility(View.VISIBLE);
        btnIncreaseScrap.setVisibility(View.VISIBLE);
    }

    /**
     * @author ljp
     * @time 17:27
     * @describe 扫描二维码返回值
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == DEVICE_NUMBER) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    deviceCode = bundle.getString(CodeUtils.RESULT_STRING);
                    //ToastUtil.showShortToast(workResultCode);
                    Log.i(TAG, "onActivityResult: ----扫描结果-----" + deviceCode);
                    etEquipmentNumber.setText(deviceCode);
                    etEquipmentNumber.setSelection(deviceCode.length());
                    linearShow.setVisibility(View.GONE);
                    layoutGone();
                    setEnableTrue();
                    httpListData();
                    httpListDataProgress();
                    //codeHttpData(workResultCode,1);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    ToastUtil.showShortToast("解析二维码失败", mContext);
                }
            }
        } else if (requestCode == MATERIALS_NUMBER) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String resultCodeId = bundle.getString(CodeUtils.RESULT_STRING);
                    // ToastUtil.showShortToast(result);
                    Log.i(TAG, "onActivityResult: ----扫描结果-----" + resultCodeId);
                    tvReplaceNumber.setText(resultCodeId);
                    linearReplace.setVisibility(View.VISIBLE);
                    //codeHttpData(resultCodeId,2);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    ToastUtil.showShortToast("解析二维码失败", mContext);
                }
            }
        } else if (requestCode == VEHICLE_NUMBER) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    vehicleCoding = bundle.getString(CodeUtils.RESULT_STRING);
                    // ToastUtil.showShortToast(result);
                    Log.i(TAG, "onActivityResult: ----扫描结果-----" + vehicleCoding);
                    textScanNum.setText(vehicleCoding);

                    //codeHttpData(resultCodeId,2);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    ToastUtil.showShortToast("解析二维码失败", mContext);
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
